﻿using MyBasicLib.Collections.Generic;
using System;
using System.Collections.Generic;

using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace MyBasicLib.WebApi
{
    public class CacheHandler : DelegatingHandler
    {

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var cache =  ModifiedTimeCache.Instance;
            if (request.Method != HttpMethod.Get)
                return base.SendAsync(request, cancellationToken);

            var requestUrl = System.Net.WebUtility.UrlDecode(request.RequestUri.PathAndQuery);
 
            if (request.Headers.IfModifiedSince != null)
            {
                var last = cache.GetLastModifiedTime(requestUrl);
                if (last != DateTime.MinValue && last - request.Headers.IfModifiedSince < TimeSpan.FromSeconds(1))
                {
                    var response1 = request.CreateResponse(HttpStatusCode.NotModified);
                    response1.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue();
                    response1.Headers.CacheControl.Public = true;
                    response1.Headers.CacheControl.MaxAge = TimeSpan.FromSeconds(3);

                    TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                    tcs.SetResult(response1);
                    return tcs.Task;
                }
            }
            return base.SendAsync(request, cancellationToken)
                       .ContinueWith(task =>
                       {
                           var response = task.Result;
                           if (response.StatusCode == HttpStatusCode.OK)
                           {
                               response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue();
                               response.Headers.CacheControl.Public = true;
                               response.Headers.CacheControl.MaxAge = TimeSpan.FromSeconds(3);
                               response.Content.Headers.LastModified = DateTime.UtcNow;
                               cache.UpdateItem(requestUrl);
                           }
                           return response;
                       });
        }
    }
}
